package com.example.servlettemplate.servlet;

import com.example.servlettemplate.dao.UserDAO;
import com.example.servlettemplate.pojo.User;
import com.example.servlettemplate.util.RequestUtil;
import com.example.servlettemplate.util.SystemConstants;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

    private UserDAO userDAO = new UserDAO();

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String nickname = RequestUtil.getString(req, "nickname");
        if (nickname == null) {
            error("昵称不能为空", req, resp);
            return;
        }
        HttpSession session = req.getSession();
        User sessionUser = (User)session.getAttribute(SystemConstants.SESSION_USER);
        sessionUser.setNickname(nickname);
        int result = userDAO.update(sessionUser);
        if (result == 1) {
            // 修改成功后回到登录页
            req.getRequestDispatcher(SystemConstants.PAGE_PATH + "index.jsp").forward(req, resp);
        }else {
            error("修改失败，请稍后再试", req, resp);
        }
    }

    public void error(String message, HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setAttribute("message", message);//动态错误信息message
        req.getRequestDispatcher(SystemConstants.PAGE_PATH + "user.jsp").forward(req, resp);//请求转发跳转页面
        return;
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
